package com.cz.fra.android.logic;

import java.util.ArrayList;
import java.util.List;

import com.cz.fra.android.data.FishReport.SpecieTable;
import com.cz.fra.android.entity.Specie;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.util.Log;

public class SpecieLogic {

	private static SpecieLogic instance;
	
	private ContentResolver cr;

	private Context mContext;
	
	private SpecieLogic(Context context) {
		mContext = context;
		cr = mContext.getContentResolver();
	}
	
	public static SpecieLogic getInstance(Context context) {
		if (instance == null) {
			instance = new SpecieLogic(context);
		}
		return instance;
	}
	
	public synchronized void insertSpecies(ArrayList<Specie> list) {
		if (cr == null) {
			cr = mContext.getContentResolver();
		}

		int length = list.size();
		Log.e("insertSpecieList start", System.currentTimeMillis() + "");
		ContentValues[] values = new ContentValues[length];
		for (int i = 0; i < length; i++) {
			Specie s = list.get(i);
			values[i] = s.instanceToCV();
		}
		cr.bulkInsert(SpecieTable.CONTENT_URI, values);
		synchronized (list) {
			list.clear();
		}
		Log.e("insertSpecies end", System.currentTimeMillis() + "");
	}
	
	public List<Specie> getSpecies(){
		if (cr == null) {
			cr = mContext.getContentResolver();
		}
		ArrayList<Specie> arrayList = new ArrayList<Specie>();
		Cursor cursor = cr.query(SpecieTable.CONTENT_URI, null, null, null, null);
		if (cursor.moveToFirst()) {
			do {
				Specie s = new Specie();
				s.setSpecie(cursor.getString(cursor.getColumnIndex(SpecieTable.SPECIE)));
				s.setDescription(cursor.getString(cursor.getColumnIndex(SpecieTable.DESCRIPTION)));
				arrayList.add(s);
			}while (cursor.moveToNext());
		}
		cursor.close();
		return arrayList;
		
	}
}
